package me.leiusual.sharing.util.extension

import androidx.lifecycle.LiveData
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.observers.DisposableSingleObserver
import io.reactivex.schedulers.Schedulers
import me.leiusual.sharing.repository.model.Data
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean

/**
 * 转换为LiveData
 */
fun <T> Single<T>.toLiveData(
    scheduler: Scheduler = Schedulers.io()
): LiveData<Data<T>> {
  return object : LiveData<Data<T>>() {

    private val started = AtomicBoolean(false)
    private var disposable: Disposable? = null

    override fun onActive() {
      if (started.compareAndSet(false, true)) {
        disposable = subscribeOn(scheduler)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeWith(object : DisposableSingleObserver<T>() {
              override fun onStart() {
                value = Data.Loading()
              }

              override fun onError(throwable: Throwable) {
                Timber.w(throwable)
                value = Data.Error(throwable)
              }

              override fun onSuccess(data: T) {
                value = Data.Success(data)
              }
            })
      }
    }

    override fun onInactive() {
      disposable?.dispose()
    }
  }
}